<template>
  <div class="wechat">
    <!-- 卡片视图区域 -->
    <div class="wechat_card">
      <!--搜索框与按钮-->
      <el-row :gutter="20"
              class="wechat_card_head"
              type="flex">
        <el-col :span="6">

          <el-input placeholder="输入关键字查询"
                    size="medium"
                    v-model="queryInfo.query"
                    clearable
                    @clear="getTableList"
                    @input="clearData">
            <el-button slot="append"
                       size="medium"
                       icon="el-icon-search"
                       @click="getTableList"></el-button>
          </el-input>
        </el-col>

        <el-button v-has="'2111'"
                   size="medium"
                   class="btn_head_medium"
                   type="primary"
                   @click="addDialogVisible=true"
                   icon="el-icon-circle-plus-outline">新增角色</el-button>

        <el-button v-has="'2112'"
                   size="medium"
                   type="danger"
                   @click="deleteRecordByIds"
                   icon="el-icon-remove-outline">删除</el-button>

        <!-- 表格列筛选和导出 -->
        <div class="tools_head">
          <el-popover placement="right"
                      trigger="click">
            <el-checkbox-group v-model="tableFilterData.checkBoxList">
              <template v-for="(item, i) in tableFilterData.dataNow">
                <el-checkbox :label="item.attr"
                             :key="i"
                             :checked="item.checked"
                             style="display: block;margin:10px;"
                             @change="filterFunHandle('filter',item.attr,i)">
                  {{item.label}}
                </el-checkbox>
              </template>
            </el-checkbox-group>
            <div slot="reference">
              <el-tooltip content="筛选列"
                          placement="bottom">
                <el-button size="small"
                           icon="el-icon-menu"></el-button>
              </el-tooltip>
            </div>
            <el-button size="small"
                       type="text"
                       @click="filterFunHandle('allchecked')">全选</el-button>
            <el-button size="small"
                       type="text"
                       @click="filterFunHandle('cancel')">取消全选</el-button>
          </el-popover>

        </div>

      </el-row>
      <!-- 表格区域 -->
      <el-table :data="tableFilterData.dataList"
                style="width: 100%"
                height="85%"
                border
                stripe
                size="small"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection">
        </el-table-column>
        <!-- 序号列 -->
        <el-table-column type="index"
                         label="序号"></el-table-column>
        <!-- 依次渲染表格的每列 -->
        <template v-for="(col,index) in tableFilterData.dataNow">
          <!-- 如果当前列的attr为普通类型，渲染内容即可 -->
          <el-table-column :key="index+'a'"
                           v-if="col.checked===true &&col.attr!=='state' && col.attr!=='type'&& col.attr!=='name'&& col.attr!=='roleName'"
                           align="center"
                           :prop="col.attr"
                           :label="col.label">
          </el-table-column>
          <!-- 如果当前列的attr为state，渲染为switch开关形式 -->
          <el-table-column :key="index"
                           v-if="col.checked===true &&col.attr==='state'"
                           :label="col.label">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.state"
                         @change="switchStateChanged(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <!-- 如果当前列的attr为roleName，渲染为标签形式 -->
          <el-table-column :key="index"
                           v-if="col.checked===true &&col.attr==='roleName'"
                           :label="col.label"
                           :prop="col.attr">
            <template slot-scope="scope">
              <el-tag type="success">{{scope.row.roleName}}</el-tag>
            </template>
          </el-table-column>
          <!-- 如果当前列的attr为name，将name内容渲染为标签形式 -->
          <el-table-column :key="index"
                           v-if="col.checked===true &&col.attr==='name'"
                           :label="col.label"
                           :prop="col.attr">
            <template slot-scope="scope">
              <el-tag>{{scope.row.name}}</el-tag>
            </template>
          </el-table-column>
        </template>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 分配权限按钮 -->
            <el-tooltip v-has="'2115'"
                        effect="dark"
                        content="分配权限"
                        placement="top"
                        :enterable="false">
              <el-button type="success"
                         icon="el-icon-setting"
                         size="mini"
                         @click="showSetRightDialog(scope.row)"></el-button>
            </el-tooltip>
            <!-- 编辑按钮 -->
            <el-button v-has="'2116'"
                       type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button v-has="'2117'"
                       type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="deleteRecordById(scope.row.id)"></el-button>

          </template>
        </el-table-column>

      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="this.queryInfo.pageNum"
                     :page-sizes="[3, 7, 15, 20, 30]"
                     :page-size="this.queryInfo.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total"></el-pagination>

      <!-- 添加记录的对话框 -->
      <el-dialog title="添加社区角色"
                 :visible.sync="addDialogVisible"
                 @close="addDialogClosed"
                 width="30%">
        <!-- 内容主体区 -->
        <el-form :model="addForm"
                 :rules="addFormRules"
                 ref="addFormRef"
                 label-width="100px">
          <el-form-item label="社区角色名称"
                        prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="系统角色"
                        prop="dsc">
            <el-select v-model="addForm.roleId"
                       placeholder="请选择">
              <el-option v-for="item in this.systemrolelist"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

        </el-form>
        <!-- 底部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addRecord">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改记录对话框 -->
      <el-dialog title="编辑社区角色信息"
                 :visible.sync="editDialogVisible"
                 width="30%"
                 @close="editDialogClosed">
        <el-form :model="editForm"
                 :rules="editFormRules"
                 ref="editFormRef"
                 label-width="110px">
          <el-form-item label="编号">
            <el-input v-model="editForm.id"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="社区角色名称"
                        prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="系统角色"
                        prop="dsc">
            <el-select v-model="editForm.roleId"
                       placeholder="请选择"
                       disabled>
              <el-option v-for="item in this.systemrolelist"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="editRecordInfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog title="分配权限"
                 :visible.sync="setRightDialogVisible"
                 width="50%"
                 @close="setRightDialogClosed">
        <el-tree :data="rightList"
                 show-checkbox
                 node-key="id"
                 :default-expanded-keys="checkedKeys"
                 :default-checked-keys="checkedKeys"
                 :props="defaultProps"
                 ref="treeRef"
                 @check-change="handleCheckChange"
                 :render-after-expand="false"></el-tree>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="setRightDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="distrubuteRight">确 定</el-button>
        </span>
      </el-dialog>

    </div>
  </div>

</template>
<script>
import {
  getList,
  add,
  deleteSelected,
  deleteCurrent,
  getEditInfo,
  edit,
  getDetail,
  modifySwitch,
} from "@/api/logistics/logisticsGreen.js";
export default {
  data () {
    return {
      //权限列表
      rightList: [

      ],
      // 当前分配权限的社区角色id
      currentSysCtRoleId: 0,
      // 待修改的社区角色权限信息
      editInfo: [],
      // 分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 自定义树形控件前缀命名
      defaultProps: {
        children: 'childrens',
        label: 'name'
      },
      // 当前角色被选中的菜单按钮列表
      checkedKeys: [1111, 1112],
      // 表格列筛选数据
      tableFilterData: {
        dataList: [

        ],
        dataNow: [
          { label: "	社区角色编号	", attr: "id", checked: false },
          { label: "	社区角色名称	", attr: "name", checked: true },
          // { label: "	系统角色编号	", attr: "roleId", checked: false },
          { label: "	系统角色名称	", attr: "roleName", checked: true },
          // { label: "	社区编号	", attr: "communityId", checked: false },
          // { label: "	社区名称	", attr: "communityName", checked: false },

        ],

        checkLabels: [], // 筛选列显示多选框数据
        checkBoxList: [], // 筛选列数据
        indexTwo: 0,
      },
      // 记录列表分页区的参数
      queryInfo: {
        //搜索条件
        query: "",
        // 当前页码
        pageNum: 1,
        //每页显示条数
        pageSize: 7,
      },
      // 没有查询条数限制的记录列表分页区的参数
      queryInfo2: {
        //搜索条件
        query: "",
        // 当前页码
        pageNum: 1,
        //每页显示条数
        // pageSize: 60,
      },
      total: 0,


      // 控制添加记录对话框的显示与隐藏
      addDialogVisible: false,
      // 添加记录的表单数据
      addForm: {
        id: "",
        name: "",

      },
      // 添加表单校验规则
      addFormRules: {},


      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      // 编辑表单校验规则
      editFormRules: {},


      // 控制详细信息抽屉的显示与隐藏
      drawerVisible: false,
      // 详细信息的表单数据
      detailForm: {},
      // 被选中的记录id
      selectedList: [],
      selectedStr: {
        ids: "",
      },
      deleteNow: {
        ids: "",
      },
      systemrolelist: [],
    }
  },
  created () {
    this.getTableList();

  },
  methods: {
    // 通过key获取所有选中节点
    getCheckedKeys () {
      this.checkedKeys = this.$refs.treeRef.getCheckedKeys()
      console.log(this.checkedKeys);
    },
    // 通过key设置节点
    setCheckedKeys () {
      this.$refs.treeRef.setCheckedKeys([3]);
    },
    // 重置所有节点
    resetChecked () {
      this.$refs.treeRef.setCheckedKeys([]);
    },
    // 点击确认，保存当前角色的菜单按钮配置
    ok () {
      this.getCheckedKeys()
    },
    //监听节点的复选框状态改变事件
    // 点击节点，监听当前节点是选中还是取消选中
    // 无论是选中还是取消选中，都加入待修改的editinfo中
    handleCheckChange (data, checked, indeterminate) {
      // console.log(data, checked, indeterminate);
      // 如果当前节点为按钮节点
      if (data.id > 1000) {
        // 选中当前节点，添加权限（修改按钮状态为1）
        if (checked) {
          ///如果当前节点id不是即将用于渲染的节点id，因为弹出窗口用checkedKeys渲染tree控件时也会触发handleCheckChange事件，所以需要排除这种情况
          this.editInfo.filter(function (item) {
            console.log(item.id)
            if (item.id == data.systemcommunityrolemenuchildrenId) {
              item.state = 1
            }
          })
          var obj = { id: 0, state: 0 }
          obj.id = data.systemcommunityrolemenuchildrenId
          obj.state = 1
          this.editInfo.push(obj)

        }
        //取消选中，删除权限（修改按钮状态为0）
        else {
          this.editInfo.filter(function (item) {
            if (item.id == data.systemcommunityrolemenuchildrenId) {
              item.state = 0
            }
          })
          var obj = { id: 0, state: 0 }
          obj.id = data.systemcommunityrolemenuchildrenId
          obj.state = 0
          this.editInfo.push(obj)
        }
      }
    },

    // 获取列表信息
    async getTableList () {
      const { data: res0 } = await this.$http.post("SystemroleAction/getBasicInfos")
      this.systemrolelist = res0.rows
      console.log(this.systemrolelist)

      if (this.queryInfo.query !== '')
        this.queryInfo.condition = `name like "%${this.queryInfo.query}%"`
      const { data: res } = await this.$http.get("SystemcommunityroleAction/getBasicInfos", { params: this.queryInfo })
      console.log(res)
      if (!res.success) return this.$message.error('获取表格数据失败')
      // this.$message.success('获取列表数据成功')
      this.tableFilterData.dataList = res.rows
      this.total = res.total

    },
    //监听搜索输入框
    clearData () {
      if (this.queryInfo.query == '') {
        delete this.queryInfo.condition
      }
    },

    // 监听多选框选中的所有记录
    handleSelectionChange (val) {
      // this.selectedList = val;
      this.selectedList = val.map(item => {
        return item.id;
      })
    },
    // 监听pageSize改变的事件
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getTableList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pageNum = newPage
      this.getTableList()
    },
    // 监听添加对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改对话框的关闭
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 监听分配权限对话框的关闭
    setRightDialogClosed () {
      this.$refs.treeRef.setCheckedKeys([]);
      this.$router.replace('/refresh');
    },
    // 表头列筛选功能
    filterFunHandle (type, currentItem, index) {
      if (type === 'filter') { // 筛选列
        if (event.target.checked === false) {
          this.tableFilterData.dataNow.forEach((item, index, arr) => {
            if (item.attr === currentItem) {
              return item.checked = false
            }
          })
        } else {
          this.tableFilterData.dataNow.forEach((item, index, arr) => {
            if (item.attr === currentItem) {
              return item.checked = true
            }
          })
        }
      } else if (type === 'allchecked') { // 全选
        if (this.tableFilterData.checkLabels.length === 0) {
          this.tableFilterData.dataNow.forEach((result) => {
            this.tableFilterData.checkLabels.push(result.attr)
          })
          this.tableFilterData.checkBoxList = this.tableFilterData.checkLabels // 复选框置为复选所有值，全部选择    
        } else {
          this.tableFilterData.checkBoxList = this.tableFilterData.checkLabels // 复选框置为复选所有值，全部选择
        }
        this.tableFilterData.dataNow.forEach((item, index, arr) => {
          item.checked = true
        })
      } else if (type === 'cancel') { // 取消全选
        this.tableFilterData.checkBoxList = [] // 复选框置为空，全部不选择
        this.tableFilterData.dataNow.forEach((item, index, arr) => {
          item.checked = false
        })
      }
    },




    //获取当前角色的所有菜单按钮
    async showSetRightDialog2 (rowInfo) {
      var roleId = rowInfo.roleId
      // 首先获取权限列表
      const { data: res0 } = await this.$http.get("SystemmenuAction/getSystemMenus")
      if (!res0.success) return this.$message.error('获取权限列表失败')
      this.rightList = res0.rows
      console.log("ok")
      console.log(this.rightList)
      // 然后获取当前角色的所有菜单按钮
      if (roleId !== '') {
        this.queryInfo2.query = roleId
        this.queryInfo2.condition = `roleId = ${this.queryInfo2.query}`
      }
      const { data: res } = await this.$http.get("SystemrolemenuchildrenAction/getBasicInfos", { params: this.queryInfo2 })
      if (!res.success) return this.$message.error('获取表格数据失败')
      this.setRightDialogVisible = !this.setRightDialogVisible
      // 提取出数组中的menuButtonId项组成新数组
      this.checkedKeys = res.rows.map((item, index) => {
        return item.menuButtonId
      })

      console.log(this.checkedKeys)

    },
    // 展示分配权限对话框
    async showSetRightDialog (rowInfo) {
      // 记录当前分配权限的社区角色id
      this.currentSysCtRoleId = rowInfo.id
      // 获取对应系统角色权限列表
      const { data: res0 } = await this.$http.post("SystemcommunityroleAction/getRoleOfSysMenuMap", { defineRoleId: rowInfo.id, communityId: 1 })
      if (!res0.success)
        return this.$message.error('获取权限信息失败')
      this.rightList = res0.rows
      console.log(this.rightList)


      // 获取对应社区角色的所有state为1的权限按钮列表
      if (rowInfo.id !== '') {
        this.queryInfo2.query = rowInfo.id
        this.queryInfo2.condition = `communityRoleId = ${this.queryInfo2.query} && state= 1`
      }
      const { data: res } = await this.$http.get("SystemcommunityrolemenuchildrenAction/getBasicInfos", { params: this.queryInfo2 })
      if (!res.success) return this.$message.error('获取当前社区角色开启的权限失败！')

      // 提取出数组中的menuButtonId项组成新数组
      this.checkedKeys = res.rows.map((item, index) => {
        return item.menuButtonId
      })
      console.log(this.checkedKeys)

      this.setRightDialogVisible = !this.setRightDialogVisible

    },

    // 确认分配权限,其实就是改变一下按钮状态
    async distrubuteRight () {
      // 当前社区角色与按钮关联id，单个更新对象：{id:?,state:?}
      console.log("待更新的权限按钮数组")
      console.log(this.editInfo)
      console.log("待更新的权限按钮数组")
      var data = JSON.stringify(this.editInfo);
      // 调用批量修改状态接口
      const { data: res } = await this.$http.post("SystemcommunityrolemenuchildrenAction/updateStates",
        data,
        {
          headers: { 'content-type': 'application/json;charset=utf-8' }
        }
      )
      // const { data: res } = await this.$http.post("SystemcommunityrolemenuchildrenAction/updateNoNull", this.editForm)
      // const { data: res } = await this.$http.post("SystemcommunityrolemenuchildrenAction/updateStates", this.editInfo)
      if (!res.success)
        return this.$message.error('权限分配失败')
      this.$message.success('权限分配成功')
      this.setRightDialogVisible = !this.setRightDialogVisible
    },
    // 添加记录
    async addRecord () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 获取当前登录账号的社区id
        var userInfo = window.sessionStorage.getItem("userInfo")
        var user_info = JSON.parse(userInfo)
        this.addForm.communityId = user_info.roles[0].communityId
        const { data: res } = await this.$http.post("SystemcommunityroleAction/addObject", this.addForm)
        console.log(res)
        if (!res.success) return this.$message.error('添加失败')
        this.$message.success('添加记录成功！')
        // 隐藏添加记录的对话框
        this.addDialogVisible = false
        // 重新获取记录列表数据
        this.getTableList()
      })
    },
    //删除记录（批量）
    async deleteRecordByIds () {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值为字符串confirm
      // 如果用户取消删除，返回值未字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      // 将selectList数组处理成字符串形式并赋值给selectStr的ids属性
      var str = ""
      for (var i = 0; i < this.selectedList.length - 1; i++) {
        str += this.selectedList[i] + ",";
      }
      str += this.selectedList[this.selectedList.length - 1]
      this.selectedStr.ids = str

      const { data: res } = await this.$http.post("SystemcommunityroleAction/deleteByIds", this.selectedStr)
      if (!res.success) return this.$message.error('删除记录失败！')
      this.$message.success('删除记录成功！')
      this.getTableList()

    },
    // 查看修改记录（当前记录）
    async showEditDialog (id) {
      const { data: res } = await this.$http.post("SystemcommunityroleAction/getObjectById", { id })
      if (!res.success)
        return this.$message.error('获取信息失败')
      this.editForm = res.rows[0]
      // console.log(this.editForm);
      this.editDialogVisible = !this.editDialogVisible
    },
    // 确认修改
    editRecordInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改记录信息的数据请求
        console.log(this.editForm)
        const { data: res } = await this.$http.post("SystemcommunityroleAction/updateNoNull", this.editForm)
        if (!res.success) return this.$message.error('更新信息失败！')
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getTableList()
        // 提示修改成功
        this.$message.success('更新信息成功！')

      })
    },
    // 删除（当前记录）
    async deleteRecordById (id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值为字符串confirm
      // 如果用户取消删除，返回值未字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      this.deleteNow.ids = id

      const { data: res } = await this.$http.post("SystemcommunityroleAction/deleteByIds", this.deleteNow)
      if (!res.success) return this.$message.error('删除记录失败！')
      this.$message.success('删除记录成功！')
      this.getTableList()

    },
    // 查看详情（当前记录）
    async getDetailInfo (id) {
      await getDetail(id).then((res) => {
        if (res.data.code != 200) {
          return this.$message.error('获取详情信息失败！')
        }
        this.detailForm = res.data.detailInfo
      })
      this.drawerVisible = true

    },
    // 修改switch开关状态（当前记录）
    async switchStateChanged (recordinfo) {
      console.log(recordinfo)
      await modifySwitch(recordinfo.id, recordinfo.state).then((res) => {
        if (res.data.code !== 200) {
          recordinfo.state = !recordinfo.state
          return this.$message.error('更新状态失败!')
        }
        this.$message.success('更新状态成功!')
      })

    },

  }

}


</script>
<style scoped>
.el-table {
  font-size: 13px;
}
.el-pagination {
  text-align: left;
  padding-top: 20px;
}
</style>